<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="form-box">
          <BasicForm @register="registerForm" />
        </div>
        <div class="table-box">
          <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :showIndexColumn="false"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="hasPermission(['3-2-edit', '3-2-del']) ? actionColumn : undefined"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'TriggerStuff'">
                  <span>
                    {{ record[column.key] === 0? '变化' :'等于'}}
                  </span>
              </template>
              <template v-if="column.key === 'action' && hasPermission(['3-2-edit', '3-2-del'])">
                <TableAction
                  :actions="[
                    {
                      label: '编辑',
                      icon: 'ant-design:edit-outlined',
                      ifShow: hasPermission('3-2-edit'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleEdit(record);
                      },
                    },
                    {
                      label: '删除',
                      icon: 'ant-design:delete-outlined',
                      ifShow: hasPermission('3-2-del'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleDelete(record);
                      },
                    },
                  ]"
                />
              </template>
            </template>
            <template #toolbar>
              <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
              <a-button class="btn-box-item" type="primary" @click="throttleSubmit">查询</a-button>
              <a-button
                class="btn-box-item"
                type="primary"
                @click="handleAdd"
                v-if="hasPermission('3-2-add')"
              >
                新增
              </a-button>
            </template>
          </BasicTable>
          <div class="flex py-2 items-center justify-end pagination-box">
            <a-pagination
              :show-total="(total) => `共 ${total} 条数据`"
              showSizeChanger
              size="small"
              :current="paginationInfo.data.current"
              :pageSize="paginationInfo.data.pageSize"
              :total="paginationInfo.data.total"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 新增或编辑的弹窗 -->
    <modelByDetail
      :info="detailForm"
      @register="registerByDetail"
      @submit-success="handelUpateTable"
    />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted, reactive, h } from 'vue';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { Pagination } from 'ant-design-vue';
  import modelByDetail from '/@/views/project/butlerDocking/components/modelByDetail.vue';
  import { useDebounceFn } from '@vueuse/core';
  import { getequipmentinfo, gettenantcode, getpageinfo, deleteItem } from '/@/api/butlerDocking/index';


  const APagination = Pagination;
  const { t } = useI18n();
  const { hasPermission } = usePermission();
  let loading = ref(false);
  let loadingByBtn = ref(false);
  let tableData = reactive([]);
  let Parameters = '[""]';
   // 设备类别
   let CategoryObj = [];
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });
  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '租户/企业',
      dataIndex: 'TenantCode',
    },
    {
      title: '设备',
      dataIndex: 'DeviceCode',
    },
    {
      title: '点位',
      dataIndex: 'TagName',
    },
    {
      title: '条件',
      dataIndex: 'TriggerStuff',
    },
    {
      title: '条件值',
      dataIndex: 'Value',
    },
    {
      title: '接口',
      dataIndex: 'ServerUrl',
    },
    {
      title: '参数',
      dataIndex: 'Pameter',
    },
    {
      title: '描述',
      dataIndex: 'Description',
    },
  ];
  // 操作栏
  let actionColumn = {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  let detailForm = reactive({
    type: 'add',
    data: {},
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      label: '租户',
      field: 'TenantCode',
      component: 'ApiSelect',
      componentProps: {
        api: gettenantcode,
        labelField: 'Name',
        valueField: 'Value',
        resultField: 'Data',
        params: [],
      },
      colProps: {
        span: 6,
      },

    },
    {
      field: 'DeviceCode',
      component: 'Select',
      label: '设备：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'FullName', value: 'AssetCode', key: 'AssetCode' },
      },
    },
    
  ];
  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerTable] = useTable();
  const { createConfirm, createMessage } = useMessage();
  const [registerForm, { validateFields, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  // 重置按钮点击事件
  async function handleResetFields() {
    setFieldsValue({
      searchModel: '',
      searchModelName: '',
      searchTypeName: '',
      searchTypeCategory: 0,
    });
    paginationInfo.data.current = 1;
    getTableData();
  }
  //获取设备
  async function getSearchCategory() {
    try {
      loading.value = true;

      let res = await getequipmentinfo([
        {
          AssetCode: '',
          ModelCode: '',
          TypeCode: '',
        },
      ]);

      CategoryObj = res;
      updateSchema({
        field: 'DeviceCode',
        componentProps: {
          options: CategoryObj,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取设备型号
  async function getTableData(params = {}) {
    try {
      loading.value = true;
     
      let res = await getpageinfo([
        {
          PageNO: paginationInfo.data.current,
          PageSize: paginationInfo.data.pageSize,
          ...params,
        },
      ]);
      paginationInfo.data.total = res.Total;
      tableData = res.Items;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 查询按钮点击事件
  async function handleSubmit() {
    try {
      let res = await validateFields();
      console.log(`output->res`, res);
      getTableData(res);
    } catch {}
  }
  // 新增或编辑成功事件
  function handelUpateTable() {
    detailForm.type = 'add';
    detailForm.data = {};
    closeModalByDetail();
    getTableData();
  }
  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  // 新增
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = {};

    openModalByDetail();
  }

  // 编辑
  function handleEdit(params) {
    detailForm.type = 'update';
    detailForm.data = params;

    openModalByDetail();
  }
  // 删除
  function handleDelete(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该设备（${params.DeviceCode}）`),
      onOk: async () => {
        loading.value = true;
        try {
          await deleteItem([params.Id]);
          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      },
    });
  }
 
 
  onMounted(async () => {
    getTableData();
    getSearchCategory();
  });
</script>

<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .form-box {
      padding: 5px;

      ::v-deep(.ant-form-item) {
        margin: 0 5px;
        margin-bottom: 8px;
      }
    }

    .table-box {
      flex: 1;
    }

    .btn-box {
      display: flex;
      align-items: center;

      .btn-box-item {
        margin: 0 5px;
      }
    }

    .tag::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }

  ::v-deep .ant-col:last-child {
    .ant-form-item {
      margin-bottom: 0px;
    }
  }
</style>
